package com.cgw.game.service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.hardware.display.DisplayManager;
import android.hardware.display.VirtualDisplay;
import android.media.MediaRecorder;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.os.Binder;
import android.os.Build;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import com.cgw.game.R;
import com.cgw.game.control.RecorderControl;
import com.cgw.game.ui.MainActivity;

import java.io.IOException;

public class ScreenRecorderService extends Service {
    private ScreenRecorder singleton = new ScreenRecorder();
    private int NOTITY_ID = 0;
    private NotificationManager mNotificationManager;
    private int mScreenDensity;
    private int wight;
    private int hight;
    private int mResultCode;
    private Intent mResultData;
    private MediaProjectionManager projectionManager;
    private MediaRecorder mMediaRecorder;
    private MediaProjection mediaProjection;
    private boolean isStart = false;
    private VirtualDisplay mVirtualDisplay;
    private int mServiceStartId = -1;

    @Override
    public void onCreate() {
        super.onCreate();
        NOTITY_ID = this.getPackageName().hashCode();
        mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        mMediaRecorder = new MediaRecorder();
        projectionManager = (MediaProjectionManager) getSystemService(MEDIA_PROJECTION_SERVICE);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if(mServiceStartId!=-1){
            return super.onStartCommand(intent, flags, startId);
        }
        mServiceStartId = startId;
        createNotificationChannel();
        mResultCode = intent.getIntExtra("code", -1);
        mResultData = intent.getParcelableExtra("data");
        mScreenDensity = intent.getIntExtra("mScreenDensity",1);
        wight = intent.getIntExtra("wight",1);
        hight = intent.getIntExtra("hight",1);
        mediaProjection = projectionManager.getMediaProjection(mResultCode, mResultData);
        initRecorder();
        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return singleton;
    }

    public class ScreenRecorder extends Binder implements RecorderControl {
        @Override
        public void stop() {
            if (mediaProjection != null) {
                mMediaRecorder.stop();
                mMediaRecorder.reset();
                isStart = false;
            }
        }

        @RequiresApi(api = Build.VERSION_CODES.N)
        @Override
        public boolean pause() {
            if(mMediaRecorder!=null&&isStart){
                mMediaRecorder.pause();
                isStart = false;
                return true;
            }
            return false;
        }

        @Override
        public boolean start() {
            if (mediaProjection == null) {
                return false;
            }
            if(isStart){
                return true;
            }
            if(mVirtualDisplay==null){
                mVirtualDisplay = createVirtualDisplay();
            }
            mMediaRecorder.start();
            isStart = true;
            return true;
        }

        @Override
        public boolean isStart() {
            return isStart;
        }
    }

    private void createNotificationChannel() {
        Notification.Builder builder = new Notification.Builder(this.getApplicationContext()); //获取一个Notification构造器
        Intent nfIntent = new Intent(this, MainActivity.class); //点击后跳转的界面，可以设置跳转数据

        builder.setContentIntent(PendingIntent.getActivity(this, 0, nfIntent, 0)) // 设置PendingIntent
                .setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.mipmap.ic_launcher)) // 设置下拉列表中的图标(大图标)
                .setSmallIcon(R.mipmap.ic_launcher) // 设置状态栏内的小图标
                .setContentText("启动中") // 设置上下文内容
                .setWhen(System.currentTimeMillis()); // 设置该通知发生的时间

        /*以下是对Android 8.0的适配*/
        //普通notification适配
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            builder.setChannelId("notification_id");
        }
        //前台服务notification适配
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel("notification_id", "notification_name", NotificationManager.IMPORTANCE_LOW);
            mNotificationManager.createNotificationChannel(channel);
        }

        Notification notification = builder.build(); // 获取构建好的Notification
        notification.defaults = Notification.DEFAULT_SOUND; //设置为默认的声音
        startForeground(NOTITY_ID, notification);
    }
    //初始化录制参数
    private void initRecorder() {
        try {
            if (mMediaRecorder == null) {
                return;
            }
            mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);// 音频源
            mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);// 视频源
            mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);//视频输出格式
            mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);// 视频录制格式
            mMediaRecorder.setOutputFile(getExternalFilesDir(Environment.DIRECTORY_MOVIES).getAbsolutePath() + System.currentTimeMillis() + ".mp4");//存储路径
            mMediaRecorder.setVideoSize(1080, 1920);// 设置分辨率
            mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);// 音频格式
            mMediaRecorder.setVideoFrameRate(30);//帧率
            mMediaRecorder.setVideoEncodingBitRate(5 * 1024 * 1024);//视频清晰度
            int orientataion = 0;
            mMediaRecorder.setOrientationHint(orientataion);//设置旋转方向
            mMediaRecorder.prepare();
        } catch (IOException e) {
            e.printStackTrace();
            Log.e("Recorder",e.getMessage());
        }
    }

    private VirtualDisplay createVirtualDisplay() {
        return mediaProjection.createVirtualDisplay("ScreenRecorder", wight, hight, mScreenDensity,
                DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR, mMediaRecorder.getSurface(), null, null);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mediaProjection != null) {
            mediaProjection.stop();
            mMediaRecorder.release();
            mMediaRecorder = null;
            mediaProjection = null;
        }
    }

    @Override
    public boolean onUnbind(Intent intent) {
        mNotificationManager.cancel(NOTITY_ID); //从状态栏中移除通知
        stopForeground(true);
        stopSelf(mServiceStartId);
        return true;
    }
}
